<template>
  <VPage>
    <VTable ref="tableRef" v-bind="tableOptions">
      <template #form="{ form }">
        <VGroup>
          <el-select v-model="form.input.type" style="width: 100px">
            <el-option label="对账单号" value="check_bill_no"></el-option>
            <el-option label="采购单号" value="purchase_no"></el-option>
            <el-option label="平台单号" value="platform_order_no"></el-option>
            <el-option label="计划单号" value="plan_no"></el-option>
            <el-option label="样品单号" value="source_no"></el-option>
            <el-option label="付款单号" value="payment_no"></el-option>
            <el-option label="跟踪号" value="tracking_no"></el-option>
            <el-option label="合同单号" value="contact_no"></el-option>
          </el-select>
          <VBatchInput v-model="form.input.value" class="w-60" @search="query" />
        </VGroup>
        <VGroup>
          <el-select v-model="form.skuInfo.type" class="w-28">
            <el-option label="sku" value="sku"></el-option>
            <el-option label="赛盒SKU" value="sai_he_sku"></el-option>
            <el-option label="自定义sku" value="custom_sku"></el-option>
          </el-select>
          <el-input v-model="form.skuInfo.value" placeholder="请输入" class="w-40"></el-input>
        </VGroup>
        <VSelect v-model="form.supplier_name" placeholder="供应商" type="supplierName" allow-create style="min-width: 200px" multiple collapse-tags clearable filterable />
        <VSelect v-model="form.order_source" placeholder="订单来源" :options="options.order_source || []" multiple collapse-tags filterable clearable style="min-width: 160px" />
        <VSelect v-model="form.destination_warehouse" placeholder="目的仓库" type="warehouse156" multiple collapse-tags filterable clearable style="min-width: 160px" />
        <VSelect v-model="form.purchase_type" placeholder="供应商类型" :options="options.purchase_type || []" multiple collapse-tags filterable clearable style="min-width: 160px" />
        <VSelect v-model="form.period_id" placeholder="结算方式" type="period" multiple collapse-tags filterable clearable style="min-width: 220px" />
        <VSelect v-model="form.company_id" placeholder="公司主体" :options="options.company_id || []" multiple collapse-tags filterable clearable style="min-width: 200px" />
        <VCascader v-model="form.purchase_user_id" placeholder="采购人员" multiple collapse-tags filterable clearable style="min-width: 160px" />
        <VSelect v-model="form.purchase_status" placeholder="采购状态" :options="options.purchase_status || []" multiple collapse-tags filterable clearable style="min-width: 160px" />
        <VSelect v-model="form.finance_status" placeholder="财务状态" :options="options.finance_status || []" multiple collapse-tags filterable clearable style="min-width: 160px" />
        <VGroup>
          <el-select v-model="form.dateRange.type" style="width: 100px">
            <el-option label="入库时间" value="inbound_time"></el-option>
          </el-select>
          <VDate v-model="form.dateRange.value" />
        </VGroup>
      </template>
      <template #toolbar_btns>
        <VButton auth="/purchase/manage/bill/applyPayment" type="primary" @click="handleBatch('pay')">申请付款</VButton>
        <VButton auth="/purchase/manage/bill/cancel" @click="handleBatch('cancel')">批量作废</VButton>
        <VExport auth="/purchase/manage/bill/export" mainKey="cb_id" name="check_bill" :tableRef="tableRef" task class="ml-auto" />
      </template>
    </VTable>
    <Add ref="addRef" :options="options" @success="query" />
    <Upload ref="uploadRef" :options="options" @success="query" />
    <ApplyPayment ref="applyPaymentRef" :options="options" isPurchase @success="query" />
    <PrintTemplate ref="printTemplateRef" :options="options" />
    <VLog ref="logRef" />
    <ViewImage ref="viewImageRef" />
  </VPage>
</template>
  
<script setup lang="jsx" name="Account">
import api from './api'
import Add from './components/Add'
import Upload from './components/Upload'
import PrintTemplate from './components/PrintTemplate'
import ApplyPayment from '@/views/finance/payment/components/ApplyPayment'
import { getOption } from '@/api/public'
import { ElMessage, ElMessageBox } from 'element-plus'
import { download } from '@/utils'
import { resMessage } from '@/utils/res'

const baseName = 'check_bill'
const tableRef = ref()
const historeRef = ref()
const loadings = reactive({})
// 查询
const query = () => {
  tableRef?.value.query()
}

// 添加
const addRef = ref()
// 获取options
const options = ref({})
Promise.all([
  getOption({ type: 'payment' }).then(res => res.data),
  getOption({ type: 'purchase' }).then(res => res.data),
  Promise.resolve({ test: [{ label: '没有数据', value: 1 }] })
]).then(res => {
  options.value = res.reduce((acc, cur) => (((acc = { ...acc, ...cur }), acc)), {})
})

// 批量操作
const applyPaymentRef = ref()

const handleBatch = (name) => {
  const selection = tableRef.value.$table.getCheckboxRecords()
  if (!selection.length) {
    ElMessage.warning('请先选择行')
    return
  }
  const p_ids = selection.reduce((acc, cur) => acc.concat(cur.p_id), [])
  const cb_ids = selection.reduce((acc, cur) => acc.concat(cur.cb_id), [])
  const showLoading = () => loadings[name] = true
  const closeLoading = () => loadings[name] = false
  const handle = {
    pay: () => {
      applyPaymentRef?.value.open(cb_ids, {bill: true})
    },
    cancel: () => {
      ElMessageBox.confirm('是否确认作废订单？', '作废', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
      })
        .then(() => {
          showLoading()
          api.cancel({ cb_ids }).then(res => {
            resMessage({
              res,
              success: () => {
                ElMessage.success('操作成功')
                query()
              }
            })
          }).finally(() => {
            closeLoading()
          })
        })
        .catch(() => {
          ElMessage({ type: 'info', message: '取消操作', })
        })
    },
  }
  handle[name]()
}

// 单行操作
const logRef = ref()
const uploadRef = ref()
const printTemplateRef = ref()
const viewImageRef = ref()
const handleRow = (name, row, rowIndex) => {
  const { cb_id } = row
  const showLoading = () => {
    loadings[name + rowIndex] = true
  }
  const closeLoading = () => {
    loadings[name + rowIndex] = false
  }
  const handle = {
    edit: () => {
      addRef?.value.open(cb_id)
    },
    view: () => {
      showLoading()
      printTemplateRef?.value.view(row, closeLoading)
    },
    cancel: () => {
      ElMessageBox.confirm('是否确认作废订单？', '作废', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
      })
        .then(() => {
          showLoading()
          api.cancel({ cb_ids: [cb_id] }).then(res => {
            resMessage({
              res,
              success: () => {
                ElMessage.success('操作成功')
                query()
              }
            })
          }).finally(() => {
            closeLoading()
          })
        })
        .catch(() => {
          ElMessage({ type: 'info', message: '取消操作', })
        })
    },
    download: async () => {
      showLoading()
      printTemplateRef?.value.pdf(row, closeLoading)
      // 批量下载图片
      // for (const url of row.oss_url) {
      //   var link = document.createElement('a')
      //   const filename = url.slice(url.lastIndexOf('/') + 1)
      //   link.href = url
      //   link.download = filename
      //   document.body.appendChild(link)
      //   link.click()
      //   document.body.removeChild(link)
      //   await new Promise(resolve => setTimeout(resolve, 300))
      // }
    },
    downloadBack: async () => {
      showLoading('download')
      await download(row.oss_url, true)
      closeLoading('download')
    },
    upload: () => {
      uploadRef?.value.open(cb_id)
    },
    log: () => {
      logRef?.value.open({ log_type: baseName, cb_id })
    },
  }
  handle[name]()
}

// 列表配置
const totalMoney = ref({})
const tableOptions = reactive({
  rowConfig: { height: 72 },
  showHeaderOverflow: false,
  formConfig: {
    data: {
      input: { type: 'check_bill_no', value: '' },
      skuInfo: { type: 'sku', value: '' },
      dateRange: { type: 'inbound_time', value: [], range: true },
    }
  },
  columns: [
    { type: 'checkbox', width: 40, fixed: 'left' },
    {
      title: '对账单号', field: 'check_bill_no', width: 160, slots: {
        default: ({ row }) => <div>
          <VText value={row.check_bill_no} type='link' onClick={() => handleRow('edit', row)} />
        </div>
      }
    },
    {
      width: 200, slots: {
        header: () => <div>供应商信息</div>,
        default: ({ row }) => <div>
          <VText title='供应商' value={row.supplier_name} line='2' />
          <VText title='供应商id' value={row.supplier_code} />
        </div>
      }
    },
    {
      title: '结算方式', field: 'period_name', width: 160, slots: {
        default: ({ row }) => <VText value={row.period_name} line={2} />
      }
    },
    {
      width: 230, slots: {
        header: () => <div>生成信息</div>,
        default: ({ row }) => <div>
          <VText title='采购人员'>{row.purchase_user}</VText>
          <VText title='生成时间'>{row.create_time}</VText>
        </div>
      }
    },
    {
      title: '公司主体', field: 'company_name', width: 140, slots: {
        default: ({ row }) => <VText value={row.company_name} line={2} />
      }
    },
    { title: 'sku', field: 'sku', width: 120, slots: {
      default: ({row, rowIndex}) => <VMore key={rowIndex}>
        {{
          default: (line) => (row.sku || []).map(d => <div class='w-full'>
            <VText value={d} line={line} />
          </div>)
        }}
      </VMore>
    } },
    {
      title: '图片', width: 80, slots: {
        default: ({ row }) => <VImage src={row.main_img} size="60px"></VImage>
      }
    },
    { title: '下单数量', field: 'purchase_num_sum', width: 80 },
    {
      width: 120, slots: {
        header: () => <div>含税总金额</div>,
        default: ({ row }) => row.total_price_tax_sum
      }
    },
    {
      width: 120, slots: {
        header: () => <div>不含税总金额</div>,
        default: ({ row }) => row.total_price_sum
      }
    },
    { title: '入库数量', field: 'inbound_num_sum', width: 80 },
    { title: '入库金额', field: 'total_inbound_price_sum', width: 100 },
    { title: '入库仓', field: 'inbound_warehouse_list', width: 120 },
    {
      title: '备注', width: 120, slots: {
        default: ({ row }) => <VText value={row.remark} line={3} />
      }
    },
    {
      title: '对账单回执文件', width: 150, slots: {
        default: ({ row, rowIndex }) => {
          const { oss_url } = row
          if (!oss_url?.length) return '-'
          const content = () => oss_url.map(d => <VText value={d} line={2} type='link' onClick={() => viewImageRef?.value.open(d)} />)
          return <VMore value={content} key={rowIndex} />
        }
      }
    },
    {
      title: '操作', width: 240, fixed: 'right', slots: {
        default: ({ row, rowIndex }) => {
          const { return_status } = row
          // return_status	退货单状态 1待提交 2待审核 3待仓库处理 4已处理 5已驳回 6已作废
          return [<div class='nm flex flex-wrap gap-x-2 gap-y-0'>
            <VButton auth="/purchase/manage/bill/edit" link type="primary" onClick={() => handleRow('edit', row, rowIndex)}>查看</VButton>
            <VButton auth="/purchase/manage/bill/log" link type="primary" onClick={() => handleRow('log', row, rowIndex)}>日志</VButton>
            <VButton auth="/purchase/manage/bill/cancel" link type="primary" onClick={() => handleRow('cancel', row, rowIndex)}>作废</VButton>
            <VButton auth="/purchase/manage/bill/download" link type="primary" onClick={() => handleRow('view', row, rowIndex)}>预览对账单模板</VButton>
            <VButton auth="/purchase/manage/bill/download" link type="primary" onClick={() => handleRow('download', row, rowIndex)}>下载对账单模板</VButton>
            <VButton auth="/purchase/manage/bill/upload" link type="primary" onClick={() => handleRow('upload', row, rowIndex)}>上传对账单回执</VButton>
            {row.oss_url?.length ? <VButton auth="/purchase/manage/bill/downloadBack" link type="primary" onClick={() => handleRow('downloadBack', row, rowIndex)}>下载对账单回执</VButton> : ''}
          </div>]
        }
      }
    },
  ],
  proxyConfig: {
    autoLoad: false,
    ajax: {
      query: ({ page, form }) => api.query({ ...form, ...page })
    }
  }
})
</script>
  